﻿using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;

namespace TaskKernel.Domain
{

    public static class ViewHelper
    {
        public static string TranslateStatus(this TaskStatus status)
        {
            switch (status)
            {
                case TaskStatus.New:
                    return "Новая";
                case TaskStatus.Closed:
                    return "Закрыта";
                case TaskStatus.InProgress:
                    return "Открыта";
                case TaskStatus.WaitingToClose:
                    return "Ожидает закрытия";
                default:
                    return "";
            }
        }
    }

    public class Translator
    {
        public static string IsNew()
        {
            return new LiteralHelper().SetFont(Color.Red).SetBold().Insert(TaskStatus.New.TranslateStatus());
        }

        public static string InProgress(string inputString)
        {
            return new LiteralHelper().SetBold().Insert(inputString);
        }

        public static string IsRequestClose()
        {
            return new LiteralHelper().SetFont(Color.Brown).SetBold().Insert(
                TaskStatus.WaitingToClose.TranslateStatus());
        }
    }

    public static class Tools
    {
        //public static Guid GetEnumGuid<T>(this T e)
        //{
        //    Type type = e.GetType();

        //    MemberInfo[] memInfo = type.GetMember(e.ToString());

        //    if (memInfo != null && memInfo.Length > 0)
        //    {
        //        object[] attrs = memInfo[0].GetCustomAttributes(typeof(EnumGuid),
        //                                                    false);
        //        if (attrs != null && attrs.Length > 0)
        //            return ((EnumGuid)attrs[0]).Guid;
        //    }

        //    throw new ArgumentException("Enum " + e.ToString() + " has no EnumGuid defined!");
        //}
        public static string RoleEnumDescription(this RoleEnum val)
        {
            var attributes =
                (DescriptionAttribute[])
                val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : string.Empty;
        }

        public static string ToDescriptionString<T>(this T val)
        {
            var attributes =
                (DescriptionAttribute[])
                val.GetType().GetField(val.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
            return attributes.Length > 0 ? attributes[0].Description : string.Empty;
        }

        public static byte[] ReadByteArrayFromFile(string fileName)
        {
            byte[] buff = null;
            var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            var br = new BinaryReader(fs);
            long numBytes = new FileInfo(fileName).Length;
            buff = br.ReadBytes((int)numBytes);
            return buff;
        }

        public static byte[] ReadFully(Stream stream)
        {
            const int size = 32768;
            var buffer = new byte[size];
            using (var ms = new MemoryStream())
            {
                while (true)
                {
                    int read = stream.Read(buffer, 0, buffer.Length);
                    if (read <= 0)
                        return ms.ToArray();
                    ms.Write(buffer, 0, read);
                }
            }
        }
        public static int GetMD5HashCode(byte[] content)
        {
            return Math.Abs(BitConverter.ToInt32(new MD5CryptoServiceProvider().ComputeHash(content), 0));
        }


        public static string DelDomain(string login)
        {
            return login.Remove(0, login.LastIndexOf("\\") + 1).ToLower();
        }

        public static string RedColorString(string inputString)
        {
            return new LiteralHelper().SetFont(Color.Red).Insert(inputString);
        }

        public static string ddMMyyyyToString(DateTime? date)
        {
            if (null != date)
                return String.Format("{0:dd}/{0:MM}/{0:yyyy}", (DateTime)date);
            return String.Empty;
        }

        public static DateTime? StringTodMyyyy(string date)
        {
            if (!String.IsNullOrEmpty(date))
            {
                return DateTime.ParseExact(date, "d/M/yyyy", CultureInfo.InvariantCulture,
                                           DateTimeStyles.None);
            }
            return null;
        }

        public static DateTime? StringTodMyyyyHm(string inDateTime)
        {
            DateTime outDateTime;
            if (DateTime.TryParseExact(inDateTime, "d/M/yyyyH:m", CultureInfo.InvariantCulture,
                                       DateTimeStyles.None, out outDateTime)) return outDateTime;
            return null;
        }

        public static int Int32FromString(string stringValue)
        {
            int intValue;
            if (Int32.TryParse(stringValue, out intValue)) return intValue;
            return 0;
        }

        public static string ReduceStringBySize(object eval, int size)
        {
            var inputStr = (string)eval;
            {
                if (!String.IsNullOrEmpty(inputStr))
                    return inputStr.Length <= size ? inputStr : inputStr.Substring(0, size) + "...";
            }
            return (string)eval;
        }
    }

    public class LiteralHelper
    {
        public LiteralHelper()
        {
            _before = "";
            _after = "";
        }

        private string _before { get; set; }
        private string _after { get; set; }

        public static string ParseHtml(TextReader re, ListDictionary keysValues)
        {
            string dst = "";
            string src;
            while ((src = re.ReadLine()) != null)
            {
                foreach (DictionaryEntry entry in keysValues)
                {
                    if (src.Contains(entry.Key.ToString()))
                    {
                        src = src.Replace("value=\"\"", "value=\"" + entry.Value + "\"");
                        if (src.Contains("selected"))
                        {
                            string dstStr = "<input  type=\"text\" name=\"" + entry.Key + "\" value = \"" + entry.Value +
                                            "\">";
                            src = dstStr;
                        }
                        if (src.Contains("textarea"))
                        {
                            string srcStr = "name=\"" + entry.Key + "\"></textarea>";
                            string dstStr = "name=\"" + entry.Key + "\">" + entry.Value + "</textarea>";
                            src = src.Trim();
                            src = src.Replace(srcStr, dstStr);
                        }
                        if (src.Contains("checkbox"))
                            src = src.Replace("value=\"\"", "checked value=\"\"");
                    }
                    if (src.Contains("<option>"))
                        src = src.Remove(0, src.Length);
                    if (src.Contains("</selected>"))
                        src = src.Remove(0, src.Length);
                }
                dst = dst.Insert(dst.Length, src);
            }
            return dst;
        }

        public LiteralHelper SetFont(string color)
        {
            _before += "<font color=\"" + color + "\">";
            _after = "</font>" + _after;
            return this;
        }

        public LiteralHelper SetBold()
        {
            _before += "<b>";
            _after = "</b>" + _after;
            return this;
        }

        public LiteralHelper SetHtmlSeparator()
        {
            _after = "<br>" + _after;
            return this;
        }

        public LiteralHelper SetLink(string link)
        {
            _before += "<a href=\"" + link + "\">";
            _after = "</a>" + _after;
            return this;
        }

        public string Insert(string input)
        {
            return _before + input + _after;
        }
    }

    public static class Color
    {
        public const string Red = "red";
        public const string Brown = "brown";
    };

    public static class Errors
    {
        public const int INVALID_VALUE = -1;
    }
}